<template>
  <el-dialog title="查看明细" :visible.sync="dialogFormVisible" width="1200px" @close="close" :close-on-click-modal="false" v-dialogDrag>
    <vab-query-form>
      <el-form inline ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="单据号" prop="docCode">
          <el-input v-model="form.docCode" autocomplete="off" maxlength="50" style="width: 180px" readonly></el-input>
        </el-form-item>
        <el-form-item label="单据日期" prop="docDate">
          <el-date-picker
            v-model="form.docDate"
            type="date"
            placeholder="选择日期"
            style="width: 180px"
            value-format="yyyy-MM-dd hh:mm:ss"
            readonly
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="客户名称" prop="clienteleName">
          <el-input v-model="form.clienteleName" autocomplete="off" maxlength="50" placeholder="请选择客户" style="width: 180px" readonly>
            <template slot="append"></template>
          </el-input>
        </el-form-item>
        <el-form-item label="销售人员" prop="salesman">
          <el-input v-model="form.salesman" autocomplete="off" maxlength="50" placeholder="请选择销售人员" style="width: 180px" readonly>
            <template slot="append"></template>
          </el-input>
        </el-form-item>
      </el-form>
      <el-form :model="form" :rules="rules" label-width="80px">
        <el-form-item label="备注" prop="remark">
          <el-input placeholder="请输入内容" maxlength="200" v-model="form.remark" readonly></el-input>
        </el-form-item>
      </el-form>
    </vab-query-form>

    <el-form class="listForm" :model="listForm" ref="listForm" :rules="listRules">
      <el-table
        border
        v-loading="listLoading"
        :data="listForm.list"
        :element-loading-text="elementLoadingText"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column show-overflow-tooltip align="center" min-width="160" prop="productCode" label="产品编码">
          <template slot="header">
            <span class="span_red">{{ '* ' }}</span>
            <span>产品编码</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip align="center" min-width="100" prop="productName" label="产品名称"></el-table-column>
        <el-table-column show-overflow-tooltip align="center" min-width="100" prop="spec" label="规格"></el-table-column>
        <el-table-column show-overflow-tooltip align="center" min-width="100" prop="model" label="型号"></el-table-column>
        <el-table-column show-overflow-tooltip align="center" min-width="100" prop="unitName" label="单位"></el-table-column>
        <el-table-column show-overflow-tooltip align="center" min-width="100" prop="price" label="单价">
          <template slot="header">
            <span class="span_red">{{ '* ' }}</span>
            <span>单价</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip align="center" min-width="100" prop="number" label="数量">
          <template slot="header">
            <span class="span_red">{{ '* ' }}</span>
            <span>数量</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip align="center" min-width="100" prop="amount" label="金额"></el-table-column>
        <el-table-column show-overflow-tooltip align="center" min-width="200" prop="remark" label="备注"></el-table-column>
      </el-table>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="close">关 闭</el-button>
    </div>
    <personnel ref="personnel" @fetch-data="addSalesman"></personnel>
    <clientele ref="clientele" @fetch-data="addClientele"></clientele>
    <product ref="product" @fetch-data="addProduct"></product>
  </el-dialog>
</template>

<script>
  import { doAdd, doEdit } from '@/api/sales/order'
  import { getDetailList } from '@/api/sales/orderDetail'
  import Clientele from '@/components/clientele'
  import Personnel from '@/components/personnel'
  import Product from '@/components/product'
  export default {
    name: 'SalesOrderDetail',
    components: { Clientele, Personnel, Product },
    data() {
      return {
        listLoading: false,
        elementLoadingText: '正在加载...',
        form: {
          docCode: undefined,
          docDate: undefined,
          clienteleName: undefined,
          salesman: undefined,
          remark: undefined,
        },
        rules: {
          docDate: [{ required: true, trigger: ['blur', 'change'], message: '请选择单据日期' }],
          clienteleName: [{ required: true, trigger: ['blur', 'change'], message: '请选择客户' }],
          salesman: [{ required: true, trigger: ['blur', 'change'], message: '请选择销售人员' }],
        },
        dialogFormVisible: false,
        listForm: {
          list: [],
        },
        listRules: {
          productCode: [{ required: true, trigger: ['blur', 'change'], message: '请选择产品' }],
          price: [{ required: true, trigger: ['blur', 'change'], message: '请输入入库单价' }],
          number: [{ required: true, trigger: ['blur', 'change'], message: '请输入入库数量' }],
        },
        delIds: [],
        productIndex: undefined,
      }
    },
    created() {},
    methods: {
      addProduct(data) {
        if (this.checkProductExist(data)) {
          return
        }
        if (this.productIndex != undefined) {
          let list = this.$copyObject(this.listForm.list)
          let product = list[this.productIndex]
          product.productId = data.productId
          product.productCode = data.productCode
          product.productName = data.productName
          product.categoryId = data.categoryId
          product.categoryName = data.categoryName
          product.unitId = data.unitId
          product.unitName = data.unitName
          product.model = data.model
          product.spec = data.spec
          product.price = data.price
          product.number = 1
          this.listForm.list = list
        } else {
          this.listForm.list.push(data)
        }
        this.handleTotalAmount()
        this.handleAdd()
      },
      checkProductExist(data) {
        if (this.listForm.list.length == 0) {
          return false
        }
        let ids = this.listForm.list.map((item) => item.productId)
        if (ids.includes(data.productId)) {
          return true
        }
        return false
      },
      openProduct(index) {
        this.productIndex = index
        this.$refs.product.showEdit()
      },
      addSalesman(data) {
        this.form.salesmanId = data.userId
        this.form.salesman = data.userName
      },
      openSalesman() {
        this.$refs.personnel.showEdit()
      },
      addClientele(data) {
        this.form.clienteleId = data.clienteleId
        this.form.clienteleName = data.clienteleName
      },
      openClientele() {
        this.$refs.clientele.showEdit()
      },
      handleRowAmount(row) {
        let price = new this.$Decimal(row.price)
        let number = new this.$Decimal(row.number)
        let amount = price.mul(number)
        row.amount = amount.toNumber()
        this.handleTotalAmount()
      },
      handleTotalAmount() {
        let totalAmount = new this.$Decimal(0)
        this.listForm.list.forEach((item) => {
          let price = new this.$Decimal(item.price)
          let number = new this.$Decimal(item.number)
          let amount = price.mul(number)
          item.amount = amount.toNumber()
          totalAmount = totalAmount.add(amount)
        })
        this.form.totalAmount = totalAmount
      },
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        const fields = ['price', 'number', 'amount']
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
            return
          }
          if (fields.includes(column.property)) {
            const values = data.map((item) => Number(item[column.property]))
            if (!values.every((value) => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
            } else {
              sums[index] = ''
            }
          } else {
            sums[index] = ''
          }
        })
        return sums
      },
      handleAdd() {
        this.listForm.list.push({
          productId: undefined,
          productCode: undefined,
          productName: undefined,
          categoryId: undefined,
          categoryName: undefined,
          unitId: undefined,
          unitName: undefined,
          model: undefined,
          spec: undefined,
          price: undefined,
          number: undefined,
          amount: undefined,
          remark: undefined,
        })
      },
      handleDelete(row, index) {
        if (row.orderDetailId) {
          this.delIds.push(row.orderDetailId)
        }
        let list = this.$copyObject(this.listForm.list)
        list.splice(index, 1)
        this.listForm.list = list
        this.handleTotalAmount()
      },
      showEdit(row) {
        this.form = Object.assign({}, row)
        this.getDetailList()
        this.dialogFormVisible = true
      },
      async getDetailList() {
        const { data } = await getDetailList({ orderId: this.form.orderId })
        this.listForm.list = data
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.listForm.list = []
        this.dialogFormVisible = false
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          this.$refs['listForm'].validate(async (listFormValid) => {
            if (valid && listFormValid) {
              this.close()
            } else {
              return false
            }
          })
        })
      },
      callbackFun(res) {
        if (res.success) {
          this.$baseMessage(res.msg, 'success')
          this.$emit('fetch-data')
          this.close()
        } else {
          this.$baseMessage(res.msg, 'error')
        }
      },
    },
  }
</script>

<style lang="scss" scoped>
  .listForm {
    ::v-deep .el-tooltip {
      .el-form-item {
        margin-bottom: 0px;
        .el-form-item__error {
          display: none;
        }
      }
    }
  }
  .span_red {
    color: #ff0000;
  }
</style>
